package com.example.concurrentprogramming8016.semaphore;

import lombok.extern.slf4j.Slf4j;

import java.sql.Timestamp;
import java.util.concurrent.*;


/**
 * @author liyanhao
 * @Date 2023-01-06 17:41
 * 可以用做流量控制 公共资源有限的应用场景
 * 实现一个同时只能处理5个请求的限流器
 */
@Slf4j
public class SemaphoneDemo2 {
    private static Semaphore semaphore = new Semaphore(5);
    //定义线程池
    private static ThreadPoolExecutor executor =
            new ThreadPoolExecutor(10, 50, 60,
                    TimeUnit.SECONDS, new LinkedBlockingQueue<>(200));

    //模拟执行方法
    public static void exec() {
        try {
            semaphore.acquire(1);
            //模拟真实方法执行
            log.info("执行exec方法");
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            semaphore.release(1);
        }
    }

    public static void main(String[] args) {
        for (; ; ) {
            try {
                TimeUnit.MILLISECONDS.sleep(100);
                //模拟请求以10个每秒的速度执行
                executor.execute(() -> {
                    exec();
                });
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

        }
    }

}

